document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (localStorage.getItem('isLoggedIn') !== 'true') {
        window.location.href = 'login.html';
        return;
    }
    
    // 初始化设备信息
    initDeviceInfo();
    
    // 导航菜单切换
    initNavigation();
    
    // 退出登录
    document.getElementById('logout').addEventListener('click', function() {
        showModal('确认退出', '您确定要退出登录吗？', function() {
            localStorage.removeItem('isLoggedIn');
            localStorage.removeItem('username');
            window.location.href = 'login.html';
        });
    });
    
    // 设备重启
    document.getElementById('restartDevice').addEventListener('click', function() {
        showModal('确认重启', '您确定要重启设备吗？', function() {
            showNotification('设备正在重启，请稍候...');
            // 模拟设备重启
            setTimeout(function() {
                showNotification('设备已重启完成');
            }, 5000);
        });
    });
    
    // 初始化设备升级页面
    initUpgradePage();
    
    // 初始化RTSP视频预览
    initRtspPlayer();
    
    // 初始化日志管理
    initLogsManagement();
    
    // 初始化设备配置
    initDeviceSettings();
    
    // 模态框关闭事件
    document.querySelector('.close').addEventListener('click', function() {
        document.getElementById('modal').style.display = 'none';
    });
    
    document.getElementById('modalCancel').addEventListener('click', function() {
        document.getElementById('modal').style.display = 'none';
    });
});

// 初始化设备信息
function initDeviceInfo() {
    // 模拟获取设备信息 (在实际应用中应该通过API请求)
    const deviceInfo = {
        deviceName: 'TJC062 智能设备',
        deviceModel: 'TJC062-Pro',
        serialNumber: 'SN20230001001',
        armVersion: 'v1.2.5',
        mcuVersion: 'v0.9.3',
        lastUpdate: '2023-06-15 14:30:45',
        cpuUsage: '32%',
        memoryUsage: '512MB / 1024MB',
        storageSpace: '2.3GB / 16GB',
        uptime: '7天 5小时 32分钟'
    };
    
    // 更新页面显示
    document.getElementById('deviceName').textContent = deviceInfo.deviceName;
    document.getElementById('deviceModel').textContent = deviceInfo.deviceModel;
    document.getElementById('serialNumber').textContent = deviceInfo.serialNumber;
    document.getElementById('armVersion').textContent = deviceInfo.armVersion;
    document.getElementById('mcuVersion').textContent = deviceInfo.mcuVersion;
    document.getElementById('lastUpdate').textContent = deviceInfo.lastUpdate;
    document.getElementById('cpuUsage').textContent = deviceInfo.cpuUsage;
    document.getElementById('memoryUsage').textContent = deviceInfo.memoryUsage;
    document.getElementById('storageSpace').textContent = deviceInfo.storageSpace;
    document.getElementById('uptime').textContent = deviceInfo.uptime;
    
    // 设置系统设置表单中的设备名称
    document.getElementById('deviceNameSetting').value = deviceInfo.deviceName;
    
    // 定期更新CPU、内存等动态信息
    setInterval(updateSystemStatus, 5000);
}

// 更新系统状态信息
function updateSystemStatus() {
    // 模拟动态数据 (在实际应用中应该通过API获取)
    const cpuUsage = Math.floor(Math.random() * 50 + 20) + '%';
    const memUsed = Math.floor(Math.random() * 300 + 400);
    const memoryUsage = `${memUsed}MB / 1024MB`;
    
    document.getElementById('cpuUsage').textContent = cpuUsage;
    document.getElementById('memoryUsage').textContent = memoryUsage;
    
    // 更新运行时间
    const uptime = document.getElementById('uptime').textContent;
    const uptimeParts = uptime.match(/(\d+)天 (\d+)小时 (\d+)分钟/);
    if (uptimeParts) {
        let days = parseInt(uptimeParts[1]);
        let hours = parseInt(uptimeParts[2]);
        let minutes = parseInt(uptimeParts[3]) + 5; // 每5秒钟更新一次，模拟5分钟过去
        
        if (minutes >= 60) {
            hours += Math.floor(minutes / 60);
            minutes = minutes % 60;
        }
        
        if (hours >= 24) {
            days += Math.floor(hours / 24);
            hours = hours % 24;
        }
        
        document.getElementById('uptime').textContent = `${days}天 ${hours}小时 ${minutes}分钟`;
    }
}

// 初始化导航菜单
function initNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    const contentSections = document.querySelectorAll('.content-section');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            const target = this.getAttribute('data-target');
            
            // 更新活动导航项
            navItems.forEach(navItem => navItem.classList.remove('active'));
            this.classList.add('active');
            
            // 显示对应内容
            contentSections.forEach(section => {
                section.classList.remove('active');
                if (section.id === target) {
                    section.classList.add('active');
                }
            });
        });
    });
}

// 初始化设备升级页面
function initUpgradePage() {
    // 显示当前版本信息
    document.getElementById('armCurrentVersion').textContent = 'v1.2.5';
    document.getElementById('mcuCurrentVersion').textContent = 'v0.9.3';
    
    // 检查ARM更新
    document.getElementById('checkArmUpdate').addEventListener('click', function() {
        showNotification('正在检查ARM固件更新...');
        
        // 模拟检查更新
        setTimeout(function() {
            const latestVersion = 'v1.3.0';
            document.getElementById('armLatestVersion').textContent = latestVersion;
            
            if (latestVersion !== document.getElementById('armCurrentVersion').textContent) {
                showNotification('发现新版本 ' + latestVersion);
                document.getElementById('upgradeArm').disabled = false;
            } else {
                showNotification('当前已是最新版本');
            }
        }, 1500);
    });
    
    // 检查MCU更新
    document.getElementById('checkMcuUpdate').addEventListener('click', function() {
        showNotification('正在检查MCU固件更新...');
        
        // 模拟检查更新
        setTimeout(function() {
            const latestVersion = 'v0.9.3'; // 假设没有新版本
            document.getElementById('mcuLatestVersion').textContent = latestVersion;
            
            if (latestVersion !== document.getElementById('mcuCurrentVersion').textContent) {
                showNotification('发现新版本 ' + latestVersion);
                document.getElementById('upgradeMcu').disabled = false;
            } else {
                showNotification('当前已是最新版本');
            }
        }, 1500);
    });
    
    // ARM升级按钮
    document.getElementById('upgradeArm').addEventListener('click', function() {
        startUpgrade('ARM');
    });
    
    // MCU升级按钮
    document.getElementById('upgradeMcu').addEventListener('click', function() {
        startUpgrade('MCU');
    });
    
    // 上传ARM固件
    document.getElementById('uploadArmFirmware').addEventListener('click', function() {
        const fileInput = document.getElementById('armFirmwareFile');
        if (fileInput.files.length === 0) {
            showNotification('请先选择固件文件', 'error');
            return;
        }
        
        const fileName = fileInput.files[0].name;
        showModal('确认升级', `您确定要上传并升级ARM固件 ${fileName} 吗？`, function() {
            startUpgrade('ARM', true);
        });
    });
    
    // 上传MCU固件
    document.getElementById('uploadMcuFirmware').addEventListener('click', function() {
        const fileInput = document.getElementById('mcuFirmwareFile');
        if (fileInput.files.length === 0) {
            showNotification('请先选择固件文件', 'error');
            return;
        }
        
        const fileName = fileInput.files[0].name;
        showModal('确认升级', `您确定要上传并升级MCU固件 ${fileName} 吗？`, function() {
            startUpgrade('MCU', true);
        });
    });
    
    // 加载更新历史
    loadUpdateHistory();
}

// 开始固件升级
function startUpgrade(type, isUpload = false) {
    // 显示升级进度条
    document.querySelector('.upgrade-progress').classList.remove('hidden');
    document.getElementById('upgradeProgressBar').style.width = '0%';
    document.getElementById('upgradeProgressText').textContent = '0%';
    document.getElementById('upgradeStatusText').textContent = `正在准备${type}固件升级...`;
    
    let progress = 0;
    const progressInterval = setInterval(function() {
        progress += 1;
        if (progress > 100) {
            clearInterval(progressInterval);
            return;
        }
        
        document.getElementById('upgradeProgressBar').style.width = progress + '%';
        document.getElementById('upgradeProgressText').textContent = progress + '%';
        
        if (progress === 20) {
            document.getElementById('upgradeStatusText').textContent = `正在下载${type}固件...`;
        } else if (progress === 50) {
            document.getElementById('upgradeStatusText').textContent = `正在校验${type}固件...`;
        } else if (progress === 70) {
            document.getElementById('upgradeStatusText').textContent = `正在安装${type}固件...`;
        } else if (progress === 90) {
            document.getElementById('upgradeStatusText').textContent = `正在重启${type}...`;
        } else if (progress === 100) {
            document.getElementById('upgradeStatusText').textContent = `${type}升级完成`;
            showNotification(`${type}固件升级成功`);
            
            // 更新版本号
            if (type === 'ARM') {
                document.getElementById('armCurrentVersion').textContent = document.getElementById('armLatestVersion').textContent;
                document.getElementById('upgradeArm').disabled = true;
                document.getElementById('armVersion').textContent = document.getElementById('armLatestVersion').textContent;
            } else {
                document.getElementById('mcuCurrentVersion').textContent = document.getElementById('mcuLatestVersion').textContent;
                document.getElementById('upgradeMcu').disabled = true;
                document.getElementById('mcuVersion').textContent = document.getElementById('mcuLatestVersion').textContent;
            }
            
            // 更新最后更新时间
            const now = new Date();
            const dateString = `${now.getFullYear()}-${padZero(now.getMonth()+1)}-${padZero(now.getDate())} ${padZero(now.getHours())}:${padZero(now.getMinutes())}:${padZero(now.getSeconds())}`;
            document.getElementById('lastUpdate').textContent = dateString;
            
            // 添加更新记录
            addUpdateLog(type);
            
            // 隐藏进度条
            setTimeout(function() {
                document.querySelector('.upgrade-progress').classList.add('hidden');
            }, 3000);
        }
    }, 100);
}

// 日期时间补零
function padZero(num) {
    return num.toString().padStart(2, '0');
}

// 加载更新历史
function loadUpdateHistory() {
    const updateLogs = [
        { date: '2023-06-15 14:30:45', type: 'ARM', version: 'v1.2.5', notes: '优化系统性能，修复了多项安全漏洞' },
        { date: '2023-05-10 09:15:22', type: 'MCU', version: 'v0.9.3', notes: '改进电源管理，提高稳定性' },
        { date: '2023-04-22 16:45:33', type: 'ARM', version: 'v1.2.0', notes: '添加新功能：支持RTSP流推送' },
        { date: '2023-03-18 11:20:15', type: 'MCU', version: 'v0.9.0', notes: '初始版本发布' }
    ];
    
    const logsContainer = document.getElementById('updateLogs');
    logsContainer.innerHTML = '';
    
    updateLogs.forEach(log => {
        const logItem = document.createElement('div');
        logItem.className = 'update-log-item';
        logItem.innerHTML = `
            <h4>${log.type} ${log.version}</h4>
            <p>${log.notes}</p>
            <p class="update-log-date">${log.date}</p>
        `;
        logsContainer.appendChild(logItem);
    });
}

// 添加更新日志
function addUpdateLog(type) {
    const now = new Date();
    const dateString = `${now.getFullYear()}-${padZero(now.getMonth()+1)}-${padZero(now.getDate())} ${padZero(now.getHours())}:${padZero(now.getMinutes())}:${padZero(now.getSeconds())}`;
    
    const version = (type === 'ARM') ? document.getElementById('armLatestVersion').textContent : document.getElementById('mcuLatestVersion').textContent;
    
    const logItem = document.createElement('div');
    logItem.className = 'update-log-item';
    logItem.innerHTML = `
        <h4>${type} ${version}</h4>
        <p>成功升级到新版本</p>
        <p class="update-log-date">${dateString}</p>
    `;
    
    const logsContainer = document.getElementById('updateLogs');
    logsContainer.insertBefore(logItem, logsContainer.firstChild);
}

// 初始化RTSP播放器
function initRtspPlayer() {
    const connectBtn = document.getElementById('connectRtsp');
    const disconnectBtn = document.getElementById('disconnectRtsp');
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    const snapshotBtn = document.getElementById('snapshotBtn');
    const rtspPlayerContainer = document.getElementById('rtspPlayer');
    let player = null;
    
    // 初始状态显示
    rtspPlayerContainer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">未连接</div>';
    
    // 设置默认RTSP URL
    if (!document.getElementById('rtspUrl').value) {
        document.getElementById('rtspUrl').value = 'rtsp://example.com/stream';
    }
    
    // 连接按钮
    connectBtn.addEventListener('click', function() {
        const rtspUrl = document.getElementById('rtspUrl').value;
        if (!rtspUrl) {
            showNotification('请输入RTSP URL', 'error');
            return;
        }
        
        showNotification('正在连接到视频流...');
        
        // 创建播放器实例
        if (player) {
            player.stop();
        }
        
        try {
            player = new RtspPlayer(rtspPlayerContainer, {
                autoplay: true,
                muted: true,
                controls: true
            });
            
            // 连接成功事件
            rtspPlayerContainer.addEventListener('rtsp:playing', function() {
                showNotification('视频流连接成功', 'success');
            }, { once: true });
            
            // 连接失败事件
            rtspPlayerContainer.addEventListener('rtsp:error', function(e) {
                showNotification('视频流连接失败: ' + e.detail.message, 'error');
            });
            
            // 连接RTSP流
            player.connect(rtspUrl);
        } catch (error) {
            console.error('播放器初始化失败:', error);
            showNotification('播放器初始化失败', 'error');
        }
    });
    
    // 断开按钮
    disconnectBtn.addEventListener('click', function() {
        if (player) {
            player.stop();
            rtspPlayerContainer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">未连接</div>';
            showNotification('已断开视频连接');
        }
    });
    
    // 全屏按钮
    fullscreenBtn.addEventListener('click', function() {
        if (player) {
            player.toggleFullscreen();
        } else {
            showNotification('请先连接视频流', 'error');
        }
    });
    
    // 截图按钮
    snapshotBtn.addEventListener('click', function() {
        if (!player) {
            showNotification('请先连接视频流', 'error');
            return;
        }
        
        const imageUrl = player.takeSnapshot();
        if (imageUrl) {
            // 创建下载链接
            const link = document.createElement('a');
            link.href = imageUrl;
            link.download = `snapshot_${new Date().getTime()}.png`;
            link.click();
            showNotification('截图已保存', 'success');
        } else {
            showNotification('截图失败，请重试', 'error');
        }
    });
}

// 初始化日志管理
function initLogsManagement() {
    // 设置默认日期范围 (最近7天)
    const now = new Date();
    const lastWeek = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    document.getElementById('logEndDate').valueAsDate = now;
    document.getElementById('logStartDate').valueAsDate = lastWeek;
    
    // 加载日志数据
    loadLogs();
    
    // 查询按钮
    document.getElementById('searchLogs').addEventListener('click', function() {
        loadLogs();
    });
    
    // 导出按钮
    document.getElementById('exportLogs').addEventListener('click', function() {
        exportLogs();
    });
    
    // 分页按钮
    document.getElementById('prevPage').addEventListener('click', function() {
        const currentPage = parseInt(document.getElementById('currentPage').textContent);
        if (currentPage > 1) {
            loadLogs(currentPage - 1);
        }
    });
    
    document.getElementById('nextPage').addEventListener('click', function() {
        const currentPage = parseInt(document.getElementById('currentPage').textContent);
        const totalPages = parseInt(document.getElementById('totalPages').textContent);
        if (currentPage < totalPages) {
            loadLogs(currentPage + 1);
        }
    });
}

// 加载日志数据
function loadLogs(page = 1) {
    const logType = document.getElementById('logType').value;
    const startDate = document.getElementById('logStartDate').value;
    const endDate = document.getElementById('logEndDate').value;
    
    // 模拟API请求加载日志
    showNotification('正在加载日志数据...');
    
    // 模拟API延迟
    setTimeout(function() {
        // 生成模拟日志数据
        const logs = generateMockLogs(logType, startDate, endDate);
        
        // 分页处理
        const pageSize = 10;
        const totalPages = Math.ceil(logs.length / pageSize);
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const currentPageLogs = logs.slice(startIndex, endIndex);
        
        // 更新分页信息
        document.getElementById('currentPage').textContent = page;
        document.getElementById('totalPages').textContent = totalPages || 1;
        
        // 启用/禁用分页按钮
        document.getElementById('prevPage').disabled = page <= 1;
        document.getElementById('nextPage').disabled = page >= totalPages;
        
        // 渲染日志表格
        renderLogs(currentPageLogs);
        
        showNotification('日志加载完成');
    }, 800);
}

// 生成模拟日志数据
function generateMockLogs(type, startDate, endDate) {
    const logs = [];
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    // 日志类型映射
    const types = ['system', 'upgrade', 'error'];
    const levels = ['info', 'warning', 'error', 'debug'];
    
    // 系统日志内容模板
    const systemLogTemplates = [
        '系统启动完成',
        '网络接口已连接',
        '设备监测模块初始化',
        'RTSP服务已启动',
        'NTP时间同步完成',
        '网络配置已更新',
        '系统资源监控开始'
    ];
    
    // 升级日志内容模板
    const upgradeLogTemplates = [
        'ARM固件升级开始',
        'MCU固件升级开始',
        '下载固件包完成',
        '验证固件包校验和',
        '备份当前固件',
        '写入新固件完成',
        '升级流程结束',
        '固件升级失败: 校验和不匹配',
        '设备重启以完成升级'
    ];
    
    // 错误日志内容模板
    const errorLogTemplates = [
        '连接服务器失败',
        '内存不足警告',
        '存储空间不足',
        'MCU通信超时',
        '无法访问配置文件',
        'RTSP流推送失败',
        '网络接口断开连接'
    ];
    
    // 生成模拟日志
    const daysRange = Math.floor((end - start) / (24 * 60 * 60 * 1000)) + 1;
    const logsCount = daysRange * 20; // 每天约20条日志
    
    for (let i = 0; i < logsCount; i++) {
        // 随机日期时间 (在开始和结束日期之间)
        const randomTime = start.getTime() + Math.random() * (end.getTime() - start.getTime());
        const logDate = new Date(randomTime);
        
        // 随机日志类型和级别
        const logType = types[Math.floor(Math.random() * types.length)];
        let logLevel;
        
        // 根据日志类型分配合适的级别和内容
        let logContent;
        if (logType === 'system') {
            logLevel = Math.random() > 0.2 ? 'info' : 'debug';
            logContent = systemLogTemplates[Math.floor(Math.random() * systemLogTemplates.length)];
        } else if (logType === 'upgrade') {
            const isError = Math.random() < 0.1;
            logLevel = isError ? 'error' : (Math.random() > 0.7 ? 'warning' : 'info');
            logContent = upgradeLogTemplates[Math.floor(Math.random() * upgradeLogTemplates.length)];
        } else { // error
            logLevel = Math.random() > 0.3 ? 'error' : 'warning';
            logContent = errorLogTemplates[Math.floor(Math.random() * errorLogTemplates.length)];
        }
        
        // 如果筛选了特定类型，则只包含该类型
        if (type !== 'all' && logType !== type) continue;
        
        logs.push({
            date: logDate,
            type: logType,
            level: logLevel,
            content: logContent
        });
    }
    
    // 按时间排序 (最新的在前)
    logs.sort((a, b) => b.date - a.date);
    
    return logs;
}

// 渲染日志表格
function renderLogs(logs) {
    const tableBody = document.getElementById('logsTableBody');
    tableBody.innerHTML = '';
    
    if (logs.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="4" style="text-align:center;">没有找到符合条件的日志</td>';
        tableBody.appendChild(row);
        return;
    }
    
    logs.forEach(log => {
        const row = document.createElement('tr');
        
        // 格式化日期时间
        const dateStr = `${log.date.getFullYear()}-${padZero(log.date.getMonth()+1)}-${padZero(log.date.getDate())} ${padZero(log.date.getHours())}:${padZero(log.date.getMinutes())}:${padZero(log.date.getSeconds())}`;
        
        // 根据日志级别添加不同的样式
        const levelClass = `log-level log-level-${log.level}`;
        
        row.innerHTML = `
            <td>${dateStr}</td>
            <td>${log.type === 'system' ? '系统' : (log.type === 'upgrade' ? '升级' : '错误')}</td>
            <td><span class="${levelClass}">${log.level === 'info' ? '信息' : (log.level === 'warning' ? '警告' : (log.level === 'error' ? '错误' : '调试'))}</span></td>
            <td>${log.content}</td>
        `;
        
        tableBody.appendChild(row);
    });
}

// 导出日志
function exportLogs() {
    const logType = document.getElementById('logType').value;
    const startDate = document.getElementById('logStartDate').value;
    const endDate = document.getElementById('logEndDate').value;
    
    // 显示导出进度
    showNotification('正在准备导出日志...');
    
    // 模拟导出延迟
    setTimeout(function() {
        // 生成所有符合条件的日志
        const logs = generateMockLogs(logType, startDate, endDate);
        
        // 创建CSV内容
        let csvContent = 'data:text/csv;charset=utf-8,时间,类型,级别,内容\n';
        
        logs.forEach(log => {
            const dateStr = `${log.date.getFullYear()}-${padZero(log.date.getMonth()+1)}-${padZero(log.date.getDate())} ${padZero(log.date.getHours())}:${padZero(log.date.getMinutes())}:${padZero(log.date.getSeconds())}`;
            const typeStr = log.type === 'system' ? '系统' : (log.type === 'upgrade' ? '升级' : '错误');
            const levelStr = log.level === 'info' ? '信息' : (log.level === 'warning' ? '警告' : (log.level === 'error' ? '错误' : '调试'));
            
            // 转义内容中的逗号，确保CSV格式正确
            const content = log.content.replace(/,/g, '，');
            
            csvContent += `${dateStr},${typeStr},${levelStr},${content}\n`;
        });
        
        // 创建下载链接并触发下载
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', `device_logs_${startDate}_to_${endDate}.csv`);
        document.body.appendChild(link);
        
        link.click();
        document.body.removeChild(link);
        
        showNotification('日志导出成功');
    }, 1500);
}

// 初始化设备配置
function initDeviceSettings() {
    // 网络设置表单
    const networkSettingsForm = document.getElementById('networkSettingsForm');
    const networkMode = document.getElementById('networkMode');
    const staticIpSettings = document.querySelector('.static-ip-settings');
    
    // 根据网络模式显示或隐藏静态IP设置
    networkMode.addEventListener('change', function() {
        staticIpSettings.style.display = this.value === 'static' ? 'block' : 'none';
    });
    
    // 初始隐藏静态IP设置
    staticIpSettings.style.display = 'none';
    
    // 模拟加载设备配置
    setTimeout(loadDeviceSettings, 500);
    
    // 网络设置表单提交
    networkSettingsForm.addEventListener('submit', function(e) {
        e.preventDefault();
        saveNetworkSettings();
    });
    
    // RTSP设置表单提交
    document.getElementById('rtspSettingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveRtspSettings();
    });
    
    // 系统设置表单提交
    document.getElementById('systemSettingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveSystemSettings();
    });
    
    // 用户设置表单提交
    document.getElementById('userSettingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveUserSettings();
    });
}

// 加载设备配置
function loadDeviceSettings() {
    // 模拟获取设备配置
    const deviceSettings = {
        network: {
            mode: 'dhcp',
            ipAddress: '192.168.1.100',
            subnetMask: '255.255.255.0',
            gateway: '192.168.1.1',
            dns: '8.8.8.8'
        },
        rtsp: {
            port: 8554,
            videoResolution: '1280x720',
            videoBitrate: 2000,
            videoFramerate: 30
        },
        system: {
            deviceName: 'TJC062 智能设备',
            ntpServer: 'pool.ntp.org',
            timeZone: 'GMT+8',
            autoUpdate: true
        }
    };
    
    // 设置网络表单值
    document.getElementById('networkMode').value = deviceSettings.network.mode;
    document.getElementById('ipAddress').value = deviceSettings.network.ipAddress;
    document.getElementById('subnetMask').value = deviceSettings.network.subnetMask;
    document.getElementById('gateway').value = deviceSettings.network.gateway;
    document.getElementById('dns').value = deviceSettings.network.dns;
    
    // 设置RTSP表单值
    document.getElementById('rtspPort').value = deviceSettings.rtsp.port;
    document.getElementById('videoResolution').value = deviceSettings.rtsp.videoResolution;
    document.getElementById('videoBitrate').value = deviceSettings.rtsp.videoBitrate;
    document.getElementById('videoFramerate').value = deviceSettings.rtsp.videoFramerate;
    
    // 设置系统表单值
    document.getElementById('deviceNameSetting').value = deviceSettings.system.deviceName;
    document.getElementById('ntpServer').value = deviceSettings.system.ntpServer;
    document.getElementById('timeZone').value = deviceSettings.system.timeZone;
    document.getElementById('autoUpdate').checked = deviceSettings.system.autoUpdate;
}

// 保存网络设置
function saveNetworkSettings() {
    const mode = document.getElementById('networkMode').value;
    const ipAddress = document.getElementById('ipAddress').value;
    const subnetMask = document.getElementById('subnetMask').value;
    const gateway = document.getElementById('gateway').value;
    const dns = document.getElementById('dns').value;
    
    // 静态IP模式下进行验证
    if (mode === 'static') {
        // 简单IP地址格式验证
        const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
        if (!ipRegex.test(ipAddress) || !ipRegex.test(subnetMask) || 
            !ipRegex.test(gateway) || !ipRegex.test(dns)) {
            showNotification('请输入有效的IP地址格式', 'error');
            return;
        }
    }
    
    // 显示保存中状态
    showNotification('正在保存网络设置...');
    
    // 模拟保存请求
    setTimeout(function() {
        showNotification('网络设置已保存');
    }, 1000);
}

// 保存RTSP设置
function saveRtspSettings() {
    const port = document.getElementById('rtspPort').value;
    const resolution = document.getElementById('videoResolution').value;
    const bitrate = document.getElementById('videoBitrate').value;
    const framerate = document.getElementById('videoFramerate').value;
    
    // 验证端口范围
    if (port < 1024 || port > 65535) {
        showNotification('端口号必须在1024-65535之间', 'error');
        return;
    }
    
    // 验证比特率
    if (bitrate <= 0) {
        showNotification('比特率必须大于0', 'error');
        return;
    }
    
    // 验证帧率
    if (framerate < 1 || framerate > 60) {
        showNotification('帧率必须在1-60之间', 'error');
        return;
    }
    
    // 显示保存中状态
    showNotification('正在保存RTSP设置...');
    
    // 模拟保存请求
    setTimeout(function() {
        showNotification('RTSP设置已保存，需要重启RTSP服务生效');
        
        // 更新URL输入框中的端口
        const rtspUrlInput = document.getElementById('rtspUrl');
        rtspUrlInput.value = rtspUrlInput.value.replace(/:\d+\//, ':' + port + '/');
    }, 1000);
}

// 保存系统设置
function saveSystemSettings() {
    const deviceName = document.getElementById('deviceNameSetting').value;
    const ntpServer = document.getElementById('ntpServer').value;
    const timeZone = document.getElementById('timeZone').value;
    const autoUpdate = document.getElementById('autoUpdate').checked;
    
    if (!deviceName.trim()) {
        showNotification('设备名称不能为空', 'error');
        return;
    }
    
    // 显示保存中状态
    showNotification('正在保存系统设置...');
    
    // 模拟保存请求
    setTimeout(function() {
        // 更新设备名称
        document.getElementById('deviceName').textContent = deviceName;
        showNotification('系统设置已保存');
    }, 1000);
}

// 保存用户设置
function saveUserSettings() {
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    // 验证当前密码
    if (currentPassword !== 'admin123') { // 模拟密码验证
        showNotification('当前密码错误', 'error');
        return;
    }
    
    // 验证新密码
    if (newPassword) {
        if (newPassword.length < 6) {
            showNotification('新密码长度必须至少6个字符', 'error');
            return;
        }
        
        if (newPassword !== confirmPassword) {
            showNotification('两次输入的新密码不一致', 'error');
            return;
        }
    } else {
        showNotification('请输入新密码', 'error');
        return;
    }
    
    // 显示保存中状态
    showNotification('正在更新密码...');
    
    // 模拟保存请求
    setTimeout(function() {
        showNotification('密码已更新，下次登录时生效');
        
        // 清空表单
        document.getElementById('currentPassword').value = '';
        document.getElementById('newPassword').value = '';
        document.getElementById('confirmPassword').value = '';
    }, 1000);
}

// 显示模态框
function showModal(title, message, confirmCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalMessage').textContent = message;
    document.getElementById('modal').style.display = 'block';
    
    // 确认按钮点击处理
    const confirmButton = document.getElementById('modalConfirm');
    const cancelButton = document.getElementById('modalCancel');
    
    // 根据模态框类型调整按钮样式
    if (title.includes('重启')) {
        confirmButton.classList.add('btn-warning');
        confirmButton.classList.remove('btn-primary');
        confirmButton.textContent = '确认重启';
    } else {
        confirmButton.classList.add('btn-primary');
        confirmButton.classList.remove('btn-warning');
        confirmButton.textContent = '确认';
    }
    
    // 移除之前的事件监听器
    const newConfirmButton = confirmButton.cloneNode(true);
    confirmButton.parentNode.replaceChild(newConfirmButton, confirmButton);
    
    // 添加新的事件监听器
    newConfirmButton.addEventListener('click', function() {
        document.getElementById('modal').style.display = 'none';
        if (typeof confirmCallback === 'function') {
            confirmCallback();
        }
    });
}

// 显示通知消息
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.add('show');
        
        // 3秒后自动隐藏并移除通知
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }, 10);
}
